class Solution
{
    int row, col;
    int dx[4] = { 1,-1,0,0 };
    int dy[4] = { 0,0,1,-1 };
public:
    int maxDistance(vector<vector<int>>& grid)
    {
        queue<pair<int, int>> q1;
        row = grid.size(), col = grid[0].size();
        vector<vector<int>> ret(row, vector<int>(col, -1));
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                if (grid[i][j] == 1)
                {
                    ret[i][j] = 0;
                    q1.push({ i,j });
                }
            }
        }
        int count = 0;
        while (q1.size())
        {
            auto [a, b] = q1.front();
            q1.pop();
            for (int k = 0; k < 4; k++)
            {
                int x = a + dx[k], y = b + dy[k];
                if (x >= 0 && x < row && y >= 0 && y < col && ret[x][y] == -1)
                {
                    ret[x][y] = ret[a][b] + 1;
                    count = max(count, ret[x][y]);
                    q1.push({ x,y });
                }
            }
        }
        return count == 0 ? -1 : count;
    }
};